﻿using System;
using System.Net;
using System.Windows;
using Skyper.Phone.View;
using System.ComponentModel;
using System.Windows.Data;
using Skyper.Phone.Controls;
using System.Collections.Generic;
using Skyper.Shared;

namespace Skyper.Phone.Presenters {
	public class HomePresenter : Presenter<IHomeView> {
		#region Nested
		private class ContactPresenter : Presenter<IContactView> {
			#region Fields
			private readonly ContactModel contact;
			#endregion
			#region Constructor
			public ContactPresenter(IContactView view, ContactModel model)
				: base(view) {
				this.contact = model;
			}
			#endregion
			#region Public
			public sealed override void Refresh() {
				this.View.Text = this.contact.Fullname;
				this.View.Mood = this.contact.Mood;
				base.Refresh();
			}
			#endregion
		}
		#endregion
		#region Fields
		
		#endregion
		#region Constructor
		public HomePresenter(IHomeView view)
			: base(view) {
				this.View.Loaded += new RoutedEventHandler(View_Loaded);
				this.View.Unloaded += new RoutedEventHandler(View_Unloaded);
		}
		#endregion
		#region Private
		private void View_Unloaded(object sender, RoutedEventArgs e) {
			Globals.Cache.ContactsUpdated -= (Cache_ContactsUpdated);
		}
		private void View_Loaded(object sender, RoutedEventArgs e) {
			Globals.Cache.ContactsUpdated += (Cache_ContactsUpdated);
		}

		private void Cache_ContactsUpdated(object sender, EventArgs e) {
			//this.View.Contacts = Globals.Cache.Contacts;
			List<ContactViewControl> list = new List<ContactViewControl>();
			foreach (var contact in Globals.Cache.Contacts) {
				ContactViewControl c = new ContactViewControl();
				c.Mood = contact.Mood;
				c.Text = contact.ToString();
				new ContactPresenter(c, contact);
				list.Add(c);
			}
			this.View.Contacts = list;
		}
		#endregion
		#region Public
		public override void Refresh() {
			base.Refresh();
		}
		#endregion
	}
}
